package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.R;
import com.example.entity.Bill;
import com.example.entity.Provider;
import com.example.service.BillService;
import com.example.service.ProviderService;
import com.example.vo.BillVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/provider")
public class ProviderController {

    @Autowired
    private ProviderService providerService;

    @Autowired
    private BillService billService;

    /**
     * 员工信息分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name, String code){
        log.info("page = {},pageSize = {},name = {},code = {}" ,page,pageSize,name,code);

        //构造分页构造器
        Page pageInfo = new Page(page,pageSize);

        //构造条件构造器
        LambdaQueryWrapper<Provider> queryWrapper = new LambdaQueryWrapper();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name),Provider::getProname,name);
        queryWrapper.like(StringUtils.isNotEmpty(code),Provider::getProcode,code);
        //添加排序条件
        queryWrapper.orderByDesc(Provider::getCreationdate);

        //执行查询
        providerService.page(pageInfo,queryWrapper);

        return R.success(pageInfo);
    }

    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Provider provider){

        log.info("新增供应商，供应商信息：{}",provider.toString());


        //获得当前登录用户的id
        Long userId = (Long) request.getSession().getAttribute("user");

        provider.setCreatedby(userId);
        provider.setCreationdate(LocalDateTime.now());

        providerService.save(provider);

        return R.success("新增供应商成功");
    }


    /**
     * 根据id修改员工信息
     * @param provider
     * @return
     */
    @PutMapping
    public R<String> update(HttpServletRequest request,@RequestBody Provider provider){

        log.info(provider.toString());

        long id = Thread.currentThread().getId();
        log.info("线程id为：{}",id);
        Long userId = (Long) request.getSession().getAttribute("user");
        provider.setModifyby(userId);
        provider.setModifydate(LocalDateTime.now());
        providerService.updateById(provider);

        return R.success("供应商信息修改成功");
    }

    /**
     * 根据id查询员工信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Provider> getById(@PathVariable Long id){
        log.info("根据id查询供应商信息...");
        Provider provider = providerService.getById(id);
        if(provider != null){
            return R.success(provider);
        }
        return R.error("没有查询到对应供应商信息");
    }

    /**
     * 根据id删除供应商
     * @param id
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long id){
        log.info("删除供应商，id为：{}",id);

        // 根据供应商id查询订单信息
        List<Bill> bills = billService.list(new QueryWrapper<Bill>().eq("providerid", id));
        // 如果有订单信息则不能删除供应商
        if(!bills.isEmpty()){
            return R.error("供应商存在订单信息，无法删除供应商，需先删除相关的订单信息");
        }

        // 删除供应商信息
        providerService.removeById(id);

        return R.success("供应商信息删除成功");
    }



    @GetMapping("/all/providerDto")
    public R<List<Provider>> getAllProviderDto(){
        LambdaQueryWrapper<Provider> queryWrapper = new LambdaQueryWrapper<>();
        // 选择要查询的字段
        queryWrapper.select(Provider::getId, Provider::getProname);
        // 添加去重条件
        queryWrapper.groupBy(Provider::getProname);
        // 执行查询
        List<Provider> providers = providerService.list(queryWrapper);
        // 转换查询结果
        List<Provider> providerDTOS = providers.stream().map(p -> new Provider(p.getId(), p.getProname())).collect(Collectors.toList());
        log.info("providerDto查询成功！");
        return R.success(providerDTOS);
    }


}
